<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_actions_block_MceFolderContentAction extends m_backoffice_extends_Action
{
    public static $defaultNbImg = 24;
    
	public function execute()
	{
		$folderLang = $this->getRequestParameter("folderLang");
		$folderId = $this->getRequestParameter("folderId");
		$numPage = intval($this->getRequestParameter("numPage")) > 0 ? $this->getRequestParameter("numPage")-1 : 0;
		$nbImage = intval($this->getRequestParameter("nbImage")) > 0 ? $this->getRequestParameter("nbImage") : self::$defaultNbImg;
        $selectedId = intval($this->getRequestParameter('selectedId'));
		$search = $this->getRequestParameter("search");

		if(is_null($folderId) || !is_numeric($folderId))
		{
			$folder = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode("medias");
            $folderId = $folder->getUniqueId();
		}
		else
		{
			$folder = $this->getDocumentProvider()->getByUniqueId($folderId, $folderLang);
		}

		if($search)
		{
			$tab = Array();
            $medias = $this->getSearchMedias($folderId, $search);

			if(!empty($medias))
			{
				$tab[] = Array("title" => "Dossier actuel (".$folder->getLabel().")", "medias" => $medias);
			}
			
			if(empty($tab))
			{
				$folder = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode("medias");
				$relationsManager = f_relation_Manager::getInstance();
				$relations = $relationsManager->getChildsIdsByDocTypeRecursive($folder->getUniqueId(), "modules_backoffice/Folder", $folder->getLang());
	
				foreach ($relations as $relation)
				{
                    $medias = $this->getSearchMedias($relation["child_id"], $search);

					if(!empty($medias))
					{
						$media = $medias[0];
						$breadCrumb = $this->getBreadCrump($media->getUniqueId(), $relation["child_model"], $relation["lang"]);
						$tab[] = Array("title" => $breadCrumb, "medias" => $this->readRightsFilter($medias));
					}
				}
			}

			$this->addToModel("medias", $tab);
			$this->addToModel("nbMedia", 0);
			$this->setView('research');
			return false;
		}

        $this->addToModel("numPage", '');

		if($folder instanceof m_backoffice_documents_Folder)
		{
            if(is_null($selectedId) || $selectedId == 0)
            {
                $medias = $folder->getMedia($nbImage, $nbImage*$numPage);

                $this->addToModel("medias", $medias);
                $this->addToModel("nbMedia", $folder->getMediaNb());
            }
            else
            {
                $medias = $folder->getMedia();

                foreach($medias as $k => $media)
                {
                    if($media->getUniqueId() == $selectedId)
                    {
                        $numPage = ceil(($k+1)/$nbImage);
                        break;
                    }
                }

                $medias = array_slice($medias, $nbImage*($numPage-1), $nbImage);
                $this->addToModel("numPage", $numPage);
            }
		}
		else
		{
            if($folder instanceof m_medias_documents_Media)
            {
                $folder = $folder->getDocumentParent();

                $medias = $folder->getMedia();

                foreach($medias as $k => $media)
                {
                    if($media->getUniqueId() == $selectedId)
                    {
                        $numPage = ceil(($k+1)/$nbImage);
                        break;
                    }
                }

                $medias = array_slice($medias, $nbImage*($numPage-1), $nbImage);
                $this->addToModel("numPage", $numPage);
            }
            else
            {
                $medias = $this->getDocumentProvider()
                                    ->loadDocuments("modules_medias/media")
                                    ->addDescOrder('document_uid')
                                    ->limit(24)
                                    ->retrieveDocuments();
                
                $this->addToModel("isRoot", "true");
            }
		}

        $medias = $this->readRightsFilter($medias);
        $this->addToModel("medias", $this->readRightsFilter($medias));
        $this->addToModel("nbMedia", $folder->getMediaNb());
        $this->addToModel('folder', $folder);
		$this->setView('success');
	}	
		
	public function getBreadCrump($id, $docType, $lang)
	{
		$parents = f_relation_Manager::getInstance()->getParentsByDocType($id, $docType, $lang);
		$breadCrumb = Array();
		foreach($parents as $parent)
		{
			$breadCrumb[] = $parent->getLabel();
		}
		
		$breadCrumb = join(" &gt; ", $breadCrumb);
		return $breadCrumb;
	}

    private function getSearchMedias($childId, $search)
    {
        $medias = $this->getDocumentProvider()
                    ->loadDocuments("modules_medias/media")
                    ->isChildOf($childId, "media")
                    ->whereLike("document_label", "%".$search."%")
                    ->orLike("title", "%".$search."%")
                    ->orLike("alt", "%".$search."%")
                    ->orLike('document_uid', $search)
                    ->retrieveDocuments();
        
        return $medias;
    }

    private function readRightsFilter($medias)
    {
        $user = $this->getUserContext()->getUser();
        foreach($medias as $i => $media)
        {
            if(!$user->hasDocRight($media, 'medias', 'read'))
            {
                unset($medias[$i]);
            }
        }

        return $medias;
    }
/*
    private function getImage($medias)
    {
        foreach($medias as $key => $media)
        {
            if(!$media->isImage())
            {
                unset($medias[$key]);
            }
        }

        return $medias;
    }
 */
}